package com.app.couponsharelife.ui.main.seeding
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.graphics.drawable.AnimationDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.app.couponsharelife.R
import com.app.couponsharelife.base.LazyFragment
import com.app.couponsharelife.data.bean.*
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.ui.listener.MyMultiPurposeListener
import com.app.couponsharelife.ui.main.home.good.GoodDetailActivity
import com.app.couponsharelife.utils.LoadUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.base_refresh_head.*
import kotlinx.android.synthetic.main.fragment_good_commodity.*
import kotlinx.android.synthetic.main.good_commodity_itemrv_item.view.*
import kotlinx.android.synthetic.main.good_commodity_rvitem.view.*
import java.text.SimpleDateFormat
import java.util.*

/**
 *Created by xct on 2019/5/7
 *Description:好货专场
 */
class GoodCommodityFragment:LazyFragment() {
    private var pageIndex=1
    private var adapter:MyAdapter?=null
    private var dataList= arrayListOf<GoodsCommodityData>()
    private var minId="1"
    private val simpleDateFormat = SimpleDateFormat("MM.dd HH:mm", Locale.getDefault())
    companion object {
        fun newInstance(): GoodCommodityFragment {
            val fragment = GoodCommodityFragment()
            fragment.arguments = Bundle()
            return fragment
        }
    }
    override val viewLayoutId: Int
        get() = R.layout.fragment_good_commodity

    override fun initViews() {
        setRefresh()
        goodCommodity_rv.layoutManager= LinearLayoutManager(context)
        adapter=MyAdapter()
        goodCommodity_rv.adapter=adapter
    }

    private fun setRefresh(){
        hotsale_refreshimg.setImageResource(R.drawable.anim_refresh)
        val animationDrawable=hotsale_refreshimg.drawable as AnimationDrawable
        goodCommodity_smart.setEnableNestedScroll(true)
        goodCommodity_smart.setOnMultiPurposeListener(object : MyMultiPurposeListener {
            override fun headerReleased() {
                animationDrawable.start()
            }

            override fun headerMoving(percent: Float) {
                setAnima(percent)
            }

            override fun headerFinish() {
                hotsale_refreshimg.setImageResource(R.drawable.refresh_0)
                animationDrawable.stop()
            }

            override fun loadMore() {
                getData(false)
            }

            override fun refresh() {
                minId="1"
                getData(true)
            }

        })
    }
    private fun setAnima(vlaue:Float){
        val layoutParams=hotsale_refreshimg.layoutParams as ConstraintLayout.LayoutParams
        layoutParams.matchConstraintPercentHeight=vlaue/2
        layoutParams.dimensionRatio="0.875:1"
        hotsale_refreshimg.layoutParams=layoutParams
    }
    override fun lazyLoad() {
        getData(false)
    }
    private fun copyContent(content: String) {
        //获取剪贴板管理器：
        val cm = activity!!.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        // 创建普通字符型ClipData
        val mClipData = ClipData.newPlainText("Label", content)
        // 将ClipData内容放到系统剪贴板里。
        cm.primaryClip = mClipData
        showToastMsg("复制成功")
    }
    private fun getData(isRefresh:Boolean){
        showProgressDialog("加载中...")
        val map= HashMap<String,String>()
        map["minId"]=minId
        RetrofitWorker.retrofitWorker.getGoodsSpecial(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<GoodsCommodityBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<GoodsCommodityBean>) {
                        dismissProgressDialog()
                        if (isRefresh){
                            goodCommodity_smart.finishRefresh()
                        }else{
                            if (minId!="1"){
                                goodCommodity_smart.finishLoadMore()
                            }
                        }
                        if (minId=="1"){
                            dataList.clear()
                        }
                        if (it.code==200&&it.data!=null&&it.data!!.data!=null){
                            if (it.data!!.data!!.isNotEmpty()){
                                if (minId=="1"){
                                    goodCommodity_llerror.visibility=View.GONE
                                    goodCommodity_rv.visibility=View.VISIBLE
                                }
                                minId=it.data!!.min_id?:""
                                dataList.addAll(it.data!!.data!!)
                                adapter!!.notifyDataSetChanged()
                            }else{
                                if (minId=="1"){
                                    goodCommodity_llerror.visibility=View.VISIBLE
                                    goodCommodity_rv.visibility=View.GONE
                                }else{
                                    goodCommodity_smart.finishLoadMoreWithNoMoreData()
                                }
                            }
                        }else{
                            goodCommodity_smart.finishLoadMoreWithNoMoreData()
                            if (minId=="1"){
                                goodCommodity_llerror.visibility=View.VISIBLE
                                goodCommodity_rv.visibility=View.GONE
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        goodCommodity_llerror.visibility=View.VISIBLE
                        goodCommodity_rv.visibility=View.GONE
                        if (isRefresh){
                            goodCommodity_smart.finishRefresh()
                        }
                        goodCommodity_smart.finishLoadMoreWithNoMoreData()
                        if (e is OtherException){
                            showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错了！")
                        }
                    }

                })
    }
    private inner class MyAdapter: RecyclerView.Adapter<RecyclerView.ViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            val view= LayoutInflater.from(parent.context).inflate(R.layout.good_commodity_rvitem,parent,false)
            return MyHolder(view)
        }

        override fun getItemCount(): Int {
            return dataList.size
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            if (dataList.isNotEmpty()){
                if (holder is MyHolder){
                    val dataBean=dataList[position]
                    var html=dataBean.copy_text?:""
                    html=html.replace("&lt;","<").replace("&gt;",">").replace("<br>","\n")
                    holder.tvTitle!!.text = html//Html.fromHtml(html, MImageGetter(context!!,holder.tvTitle!!),null)
                    val time=dataBean.activity_start_time?:System.currentTimeMillis().toString()
                    holder.tvTime!!.text=if (time.isNotEmpty()){
                        if (time.length>10){
                            simpleDateFormat.format(time.toLong())
                        }else{
                            simpleDateFormat.format(time.toLong()*1000)
                        }
                    }else{
                        simpleDateFormat.format(System.currentTimeMillis())
                    }
                    val goodsData= arrayListOf<ItemData>()
                    if (dataBean.item_data!=null&&dataBean.item_data!!.isNotEmpty()){
                        holder.rvGoods!!.visibility=View.VISIBLE
                        goodsData.addAll(dataBean.item_data!!)
                        holder.rvGoods!!.layoutManager=GridLayoutManager(context,3)
                        holder.rvGoods!!.adapter=MyImagAdapter(goodsData)
                    }else{
                        holder.rvGoods!!.visibility=View.GONE
                    }
                    holder.tvCopy!!.setOnClickListener {
                        copyContent(html)
                    }
                }
            }
        }
    }
    private inner class MyHolder(itemview: View): RecyclerView.ViewHolder(itemview){
        var ivHead:ImageView?=null
        var tvNikeName: TextView?=null
        var tvTime:TextView?=null
        var tvCopy:TextView?=null
        var tvTitle:TextView?=null
        var rvGoods:RecyclerView?=null
        init {
            ivHead=itemview.ivHead
            tvNikeName=itemview.tvNikeName
            tvTime=itemview.tvTime
            tvCopy=itemview.tvCopy
            tvTitle=itemview.tvTitle
            rvGoods=itemview.rvGoods
        }
    }
    private inner class MyImagAdapter(val goodsList:ArrayList<ItemData>):RecyclerView.Adapter<RecyclerView.ViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            val view= LayoutInflater.from(parent.context).inflate(R.layout.good_commodity_itemrv_item,parent,false)
            return MyImagHolder(view)
        }
        override fun getItemCount(): Int {
            return goodsList.size
        }
        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            if (goodsList.isNotEmpty()){
                if (holder is MyImagHolder){
                    val dataBean=goodsList[position]
                    LoadUtils().loadRoundImag(context!!,holder.imag!!,dataBean.itempic?:"",R.drawable.ic_good_place_holder,5)
                    if (dataBean.itemid!=null){
                        holder.tvPrice!!.visibility=View.VISIBLE
                        holder.tvPrice!!.text="￥"+dataBean.itemendprice?:"0"
                    }else{
                        holder.tvPrice!!.visibility=View.GONE
                    }
                    holder.itemView.setOnClickListener {
                        if (dataBean.itemid!=null){
                            val goodBean=TaobaoGoodBean()
                            goodBean.item_id=dataBean.itemid?:""
                            goodBean.goodsWenAn=dataBean.itemdesc?:""
                            goodBean.volume="0"
                            goodBean.goodsSource1="好单库"
                            goodBean.small_images=""
                            goodBean.pict_url=""
                            val intent = Intent(context, GoodDetailActivity::class.java)
                            intent.putExtra("good", goodBean)
                            startActivity(intent)
                        }
                    }
                }
            }
        }
    }
    private inner class MyImagHolder(itemview:View):RecyclerView.ViewHolder(itemview){
        var imag: ImageView?=null
        var tvPrice:TextView?=null
        init {
            imag=itemview.ivGoods
            tvPrice=itemview.tvPrice
        }
    }
}